<template>
  <div style="margin-bottom: 10px">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form :model="query" ref="serchFormRef">
            <el-form-item label="标签名称" label-width="70px">
              <el-input v-model="query.keyword" placeholder="请根据文章标题搜索"></el-input>
            </el-form-item>
            <el-form-item label="状态" label-width="70px">
              <el-select v-model="query.state" placeholder="请选择状态" clearable>
                <el-option v-for="item in options" :key="item.index" :label="item.label" :value="item.state"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <el-button style="margin-left: 120px" @click="clearSearch">清除</el-button>
          <el-button type="primary" @click="getArticles">搜索</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="success" icon="el-icon-edit" style="float: right" @click="showAddDialog">新增技巧</el-button>
        </el-col>
      </el-row>
      <el-alert :title="dataNumber" type="info" show-icon> </el-alert>
      <el-table :data="items">
        <el-table-column label="序号" type="index" width="50px" align="center"></el-table-column>
        <el-table-column label="文章标题" prop="title">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
            <el-button type="text" icon="el-icon-film" v-if="scope.row.videoURL !== ''" @click="showVideo(scope.row.videoURL)"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="阅读数" prop="visits" align="center"></el-table-column>
        <el-table-column label="录入人" prop="username" align="center"></el-table-column>
        <el-table-column label="录入时间" prop="createTime"></el-table-column>
        <el-table-column label="状态" prop="state" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.state === 1">已启用</el-tag>
            <el-tag type="danger" v-else>已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="showPreview(scope.row.id)">预览</el-button>
            <el-button type="text" v-if="scope.row.state === 1" @click="turnBtn(scope.row.state, scope.row.id)">禁用</el-button>
            <el-button type="text" v-else @click="turnBtn(scope.row.state, scope.row.id)">启用</el-button>
            <el-button type="text" v-if="scope.row.state === 1" disabled>修改</el-button>
            <el-button type="text" v-else @click="showEditDialog(scope.row.id)">修改</el-button>
            <el-button type="text" v-if="scope.row.state === 1" disabled>删除</el-button>
            <el-button type="text" v-else @click="deleteTags(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page - 0"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="query.pagesize - 0"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts - 0"
      >
      </el-pagination>
    </el-card>
    <!-- 添加按钮对话框 -->
    <el-dialog title="添加文章" :visible.sync="addDialogFormVisible" width="42%">
      <el-form :model="addarticlesForm" ref="addarticlesFormRef" :rules="addFormRules">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="addarticlesForm.title" style="width: 500px" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" label-width="70px" prop="articleBody">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="addarticlesForm.articleBody" style="width: 500px"></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址">
          <el-input v-model="addarticlesForm.videoURL" style="width: 500px" placeholder="请输入视频地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addArticles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改按钮对话框 -->
    <el-dialog title="修改文章" :visible.sync="editDialogFormVisible" width="42%">
      <el-form :model="editForm" ref="editFormRef" :rules="addFormRules">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="editForm.title" style="width: 500px" placeholder="请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" label-width="70px" prop="articleBody">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="editForm.articleBody" style="width: 500px"></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址">
          <el-input v-model="editForm.videoURL" style="width: 500px" placeholder="请输入视频地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editArticles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 预览文章对话框 -->
    <el-dialog title="预览文章" :visible.sync="pwDialogVisible" width="35%" class="pwDialog">
      <h2>{{ details.title }}</h2>
      <p>
        {{ details.createTime }} {{ details.creatorID === 2 ? '超级管理员' : '录入管理员' }} <i class="el-icon-view"> {{ details.visits }}</i>
      </p>
      <div class="preview-content" v-html="details.articleBody"></div>
    </el-dialog>
    <!-- 视频对话框 -->
    <el-dialog :visible.sync="videoDialog" @close="stopVideo(videoOp.sources[0].src)">
      <video-player :options="videoOp" ref="videoPlayer"></video-player>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'articles',
  data () {
    return {
      query: {
        page: 1,
        pages: 0,
        pagesize: 10,
        keyword: ''
      },
      counts: '',
      items: [],
      options: [
        { state: 1, label: '已启用' },
        { state: 0, label: '已禁用' },
        { state: null, label: '全部' }
      ],
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      addarticlesForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      editArticlesForm: {},
      // 添加表单验证规则
      addFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入200字以内的内容', trigger: 'blur' },
          { min: 1, max: 200, message: '不得超过200字' }
        ]
      },
      editForm: {},
      details: {},
      videoDialog: false,
      pwDialogVisible: false,
      videoOp: {
        fluid: true,
        muted: false,
        autoplay: false,
        sources: [
          {
            type: 'video/mp4', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            // src: require('@/assets/vedio.mp4') // url地址
            // src: 'https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm',
            src: ''
          }
        ],
        notSupportedMessage: '此视频暂无法播放，请稍后再试' // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
      }
    }
  },
  created () {
    this.getArticles()
  },
  methods: {
    async getArticles () {
      const { data: res } = await this.$http.get('/articles', { params: this.query })
      this.items = res.items
      this.counts = res.counts
      // console.log(res)
      // console.log(this.items)
    },
    handleSizeChange (val) {
      this.query.pagesize = val
      this.getArticles()
    },
    handleCurrentChange (val) {
      this.query.page = val
      this.getArticles()
    },
    clearSearch () {
      this.query.keyword = ''
      this.$refs.serchFormRef.resetFields()
      this.getArticles()
    },
    // 显示添加文章对话框
    showAddDialog () {
      this.addDialogFormVisible = true
    },
    addArticles () {
      this.$refs.addarticlesFormRef.validate(async valid => {
        if (!valid) return
        await this.$http.post('/articles', this.addarticlesForm)
        // if (res.success !== true) return this.$message.error('添加标签失败！')
        // console.log(res)
        this.$message.success('添加文章成功！')
        this.addDialogFormVisible = false
        this.getArticles()
        this.$refs.addarticlesFormRef.resetFields()
      })
    },
    // 修改文章状态
    async turnBtn (state, id) {
      var newState = state === 1 ? 0 : 1
      const { data: res } = await this.$http.post(`/articles/${id}/${newState}`)
      if (res.success !== true) return this.$message.error('变更状态失败！')
      this.$message.success('变更状态成功！')
      this.getArticles()
    },
    // 显示修改文章对话框
    async showEditDialog (id) {
      this.editDialogFormVisible = true
      // const { data: res } = await this.$http.get(`/articles/${id}`)
      const res = await this.$http.get(`/articles/${id}`)
      this.editForm = res.data
      // console.log(this.editForm)
    },
    // 确定修改
    editArticles () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`/articles/${this.editForm.id}`, this.editForm)
        if (res.success !== true) return this.$message.error('添加标签失败！')
        // console.log(res)
        this.$message.success('修改文章成功！')
        this.$refs.editFormRef.resetFields()
        this.editDialogFormVisible = false
        this.getArticles()
      })
    },
    // 删除
    deleteTags (id) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`/articles/${id}`)
        if (res.success !== true) return this.$message.error('删除失败！')
        this.$message.success('删除成功！')
        this.getArticles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 显示视频详情
    showVideo (url) {
      this.videoDialog = true
      this.videoOp.sources[0].src = url
      this.$nextTick(() => {
        this.$refs.videoPlayer.player.play()
      })
    },
    stopVideo (src) {
      this.$refs.videoPlayer.player.pause() // 暂停
      this.$refs.videoPlayer.player.src(src) // 重置进度条
    },

    // 显示预览
    async showPreview (id) {
      this.pwDialogVisible = true
      const res = await this.$http.get(`/articles/${id}`)
      this.details = res.data
    }
  },
  computed: {
    dataNumber () {
      return '数据一共' + this.items.length + '条'
    },
    player () {
      return this.$refs.videoPlayer.player
    }
  }
}
</script>

<style scoped lang="less">
video {
  width: 100%;
}
.preview-content {
  background-color: #f5f5f5;
  border-top: 1px dashed rgb(204, 204, 204);
  padding: 20px 0;
}
.el-pagination {
  margin: 15px 0;
  float: right;
}
.pwDialog {
  /deep/ .el-dialog__body {
    padding: 10px 20px 30px;
  }
}
</style>
